﻿using CustomerDTO;
using J.CustomerModel;
using J.CustomerRepository.Interface;
using StatusDto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace CustomerService
{
    public class CustomerListService:ICustomerListService
    {
        private readonly ICustomerListRepository customerListRepository;
        public CustomerListService(ICustomerListRepository customerListRepository)
        {
            this.customerListRepository = customerListRepository;
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> CustomerAdd(CustomerList model)
        {
            return await customerListRepository.AddAsync(model);
        }

        /// <summary>
        /// 客户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<CustomerList> CustomerDetail(int id)
        {
            return await customerListRepository.GetModelAsync(id);
        }
        /// <summary>
        /// 显示客户列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="customerName"></param>
        /// <returns></returns>
        public async Task<PageDto<CustomerList>> GetCustomerShow(CustomerShowDto customerDto)
        {

            var list = await customerListRepository.QueryListByAsync(x =>
        (string.IsNullOrEmpty(customerDto.customerName) || x.CustomerName.Contains(customerDto.customerName)) &&
        (customerDto.phonenumber == null || x.PhoneNumber.Contains(customerDto.phonenumber))
    );

            int PageTotal = list.Count();
            int PageCount = (int)Math.Ceiling(list.Count() * 1.0 / customerDto.pageSize);
            list = list.OrderByDescending(x => x.CustomerId).Skip((customerDto.pageIndex - 1) * customerDto.pageSize).Take(customerDto.pageSize).ToList();
            return new PageDto<CustomerList>
            {
                Data = list,
                pagedCount = PageCount,
                pageIndex = customerDto.pageIndex,
                pageSize = customerDto.pageSize,
                totalCount = PageTotal
            };
        }
        /// <summary>
        /// 通过手机号查询客户
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<CustomerList>> GetCustomer(string phone)
        {
            var list = await customerListRepository.GetAllAsync();
            if (!string.IsNullOrEmpty(phone))
            {
                list = list.Where(x => x.PhoneNumber.Contains(phone)).ToList();
            }
            return list;
        }
    }
}
